<template>
  <div class="canvas-view">
    <img :src="shareImg" alt="" class="share-img" />
  </div>
</template>

<script>
import QRCode from "qrcode";
import share from "../../../../assets/share.png";
export default {
  data() {
    return {
      shareImg: "",
    };
  },
  mounted() {
    this.getShareImg();
  },
  methods: {
    //生成二维码图片
    getShareImg() {
      let shareCode = window.location.href;
      QRCode.toDataURL(shareCode, { color: { light: "#ffffff60" } }).then(
        (url) => {
          let qrcodeImg = document.createElement("img");
          qrcodeImg.src = url;
          qrcodeImg.onload = () => {
            this.buildImg(qrcodeImg);
          };
        }
      );
    },
    // canvas 绘成海报
    buildImg(qrcodeImg) {
      var canvas = document.createElement("canvas");
      let context = canvas.getContext("2d");
      let bgImg = document.createElement("img");
      bgImg.setAttribute("crossOrigin", "anonymous");
      bgImg.src = share;
      bgImg.onload = () => {
        //画布大小
        let canvasW = bgImg.width;
        let canvasH = bgImg.height;

        // 二维码大小 位置
        let codeH = canvasW / 4;
        let codeHX = 10;
        let codeHY = canvasH - codeH - 10;

        canvas.width = canvasW;
        canvas.height = canvasH;

        //设置画布大小
        canvas.style.width = canvasW + "px";
        canvas.style.height = canvasH + "px";
        context.fillStyle = "#fff"; //设置填充颜色
        context.rect(0, 0, canvasW, canvasH); //设置可填充矩形
        context.fill(); //填充颜色
        context.drawImage(bgImg, 0, 0, canvasW, canvasH); //添加图片

        //设置二维码
        context.beginPath();
        context.fillStyle = "#fff";
        context.fillRect(codeHX, codeHY, codeH, codeH);
        context.stroke();
        context.drawImage(qrcodeImg, codeHX, codeHY, codeH, codeH);

        //设置文字
        context.fillStyle = "#000"; // 设置文字颜色
        context.font = "25px Georgia";
        context.fillText("加我微信", 10, 250);

        //渐变颜色设置
        context.font = "35px Verdana";
        // 创建渐变
        let gradient = context.createLinearGradient(0, 0, canvasW, 0);

        gradient.addColorStop("0", "magenta");
        gradient.addColorStop("0.5", "blue");
        gradient.addColorStop("1.0", "red");

        context.fillStyle = gradient;
        context.fillText("扫码有惊喜哦~", 10, 290);

        this.shareImg = canvas.toDataURL("image/png"); //转化为ba64位图片地址
      };
    },
  },
};
</script>
